package com.jj.network.okhttp;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 *
 * @param <T> 请求成功的数据类型
 */

public abstract class BaseCallback<T> implements Callback {

    private static final int CALLBACK_SUCCESS = 0x01;
    private static final int CALLBACK_ERROR = 0x02;

    /**
     * 在线程中处理数据
     * @param response 请求结果
     * @return 处理结果
     */
    protected abstract T parsingData(Response response);

    /**
     * 请求成功
     *
     */
    protected abstract void onSuccess(T result);

    /**
     * 请求异常
     *
     * @param error
     */
    protected abstract void onError(String error);

    /**
     * 请求结束
     */
    protected abstract void onEnd();

    private static class UIHandler<T> extends Handler {
        private BaseCallback<T> mCallback;

        UIHandler(BaseCallback<T> callback) {
            super(Looper.getMainLooper());
            this.mCallback = callback;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mCallback == null) {
                return;
            }
            switch (msg.what) {
                case CALLBACK_SUCCESS: {
                    T success = (T) msg.obj;
                    mCallback.onSuccess(success);
                    break;
                }
                case CALLBACK_ERROR: {
                    String e = (String) msg.obj;
                    mCallback.onError(e);
                    break;
                }
                default:
                    super.handleMessage(msg);
                    break;
            }
            mCallback.onEnd();
            mCallback = null;
        }
    }

    private final UIHandler mHandler = new UIHandler<T>(this);

    @Override
    public void onFailure(Call call, IOException e) {
        Message message = Message.obtain();
        message.what = CALLBACK_ERROR;
        message.obj = e.getMessage();
        mHandler.sendMessage(message);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            Message message = Message.obtain();
            message.what = CALLBACK_SUCCESS;
            message.obj = parsingData(response);
            mHandler.sendMessage(message);
        } else {
            Message message = Message.obtain();
            message.what = CALLBACK_ERROR;
            message.obj = response.body().string();
            mHandler.sendMessage(message);
        }
    }
}
